from dash import Input, Output, State, callback_context, no_update, ALL,html
from models import db, RepairRecord,Organization
from datetime import datetime
import dash
import base64
import os,time
from modules.generatelogs.generatelogs import write_repair_log
from flask import session
from server import server


# 引入Modal组件
# from modules.repair.modals import  register_modal_callbacks
# register_modal_callbacks(dash_app)

def register_repair_respond_callbacks(dash_app):
    


    @dash_app.callback(
        [Output('repair-records-table', 'data'),
        Output('repair-records-table', 'page_count'),
        Output('repair-respond-button', 'disabled', allow_duplicate=True),
        Output('repair-complete-button', 'disabled', allow_duplicate=True),
        Output('upload-proof-btn', 'disabled'),
        Output('repair-respond-button', 'style'),
        Output('repair-complete-button', 'style'),
        Output('upload-proof-btn', 'style'),
        Output('repair-details-record-id-store', 'data', allow_duplicate=True)],  # 新增
        [Input('repair-records-table', "page_current"),
        Input('repair-records-table', "page_size"),
        Input('repair-records-table', "sort_by"),
        Input('repair-org-filter', 'value'),
        Input('repair-dept-filter', 'value'),
        Input('repair-id-filter', 'value'),
        Input('repair-status-filter', 'value'),
        Input('repair-date-filter', 'start_date'),
        Input('repair-date-filter', 'end_date'),
        Input('repair-keyword-filter', 'value'),
        Input('repair-person-filter', 'value'),
        Input('repair-caller-filter', 'value'),
        Input('repair-filter-button', 'n_clicks'),
        Input('repair-refresh-flag-answer', 'data'),
        Input('repair-refresh-flag-complete', 'data'),
        Input('repair-refresh-flag-addnew', 'data'),
        Input('repair-refresh-flag-cancel', 'data'),
        Input('repair-records-table', 'active_cell'),
        State('repair-records-table', 'data')],
        prevent_initial_call='initial_duplicate'
    )
    def update_repair_table_and_buttons(page_current, page_size, sort_by,
                            org_shortname, dept_name, equipmentID, status_filter, start_date, end_date, keyword, repair_person, repair_caller, n_clicks, refresh_flag, refresh_flag2, refresh_flag3, refresh_flag4, active_cell, table_data):
        data = []
        page_count = 0
        disabled1 = disabled2 = disabled3 = True
        style1 = style2 = style3 = {
            "cursor": "not-allowed",
            "opacity": 0.65,
            "backgroundColor": "#cccccc",
            "boxShadow": "1px 1px 3px #bbb"
        }
        selected_repair_id = None  # 在这里初始化变量
        try:
            with server.app_context():
                query = db.session.query(RepairRecord).filter(RepairRecord.is_active == 1)
                from flask import session
                user_org_code = session.get('user_org_code')
                if user_org_code and user_org_code != 'HPQWJW':
                    org_obj = Organization.query.filter_by(org_code=user_org_code).first()
                    if org_obj and org_obj.short_name_c:
                        query = query.filter(RepairRecord.org_shortname_c == org_obj.short_name_c)
                if org_shortname:
                    if isinstance(org_shortname, list):
                        org_shortname = org_shortname[0] if org_shortname else ''
                    query = query.filter(RepairRecord.org_shortname_c == org_shortname)
                if dept_name:
                    if isinstance(dept_name, list):
                        dept_name = dept_name[0] if dept_name else ''
                    query = query.filter(RepairRecord.department_name == dept_name)
                if equipmentID:
                    query = query.filter(RepairRecord.product_id == equipmentID)
                if status_filter:
                    query = query.filter(RepairRecord.repair_status == status_filter)
                if start_date:
                    query = query.filter(RepairRecord.report_date >= start_date)
                if end_date:
                    end_date_dt = datetime.strptime(end_date, '%Y-%m-%d').date() + pd.Timedelta(days=1)
                    query = query.filter(RepairRecord.report_date < end_date_dt)
                if keyword:
                    search_term = f"%{keyword}%"
                    query = query.filter(
                        (RepairRecord.product_name.like(search_term)) |
                        (RepairRecord.product_code.like(search_term)) |
                        (RepairRecord.fault_description.like(search_term))
                    )
                if repair_person:
                    if isinstance(repair_person, list):
                        repair_person_value = repair_person[0] if repair_person else None
                    else:
                        repair_person_value = repair_person
                    if repair_person_value:
                        query = query.filter(RepairRecord.repair_person == repair_person_value)
                if repair_caller:
                    if isinstance(repair_caller, list):
                        repair_caller_value = repair_caller[0] if repair_caller else None
                    else:
                        repair_caller_value = repair_caller
                    if repair_caller_value:
                        query = query.filter(RepairRecord.repair_caller == repair_caller_value)
                if sort_by:
                    for sort_item in sort_by:
                        col_id = sort_item['column_id']
                        if col_id in ['product_name', 'product_code', 'org_shortname_c', 'department_name', 'report_date', 'repair_status', 'repair_person']:
                            direction = sort_item['direction']
                            col = getattr(RepairRecord, col_id)
                            query = query.order_by(col.asc() if direction == 'asc' else col.desc())
                else:
                    query = query.order_by(RepairRecord.report_date.desc())
                total_records = query.count()
                page_count = (total_records + page_size - 1) // page_size if page_size > 0 else 1
                records = query.offset(page_current * page_size).limit(page_size).all()
                for r in records:
                    data.append({
                        'id': r.id,
                        'product_id': r.product_id,
                        'product_name': r.product_name,
                        'org_shortname': r.org_shortname_c,
                        'department_name': r.department_name,
                        'fault_description': r.fault_description,
                        'report_date': r.report_date.strftime('%Y-%m-%d %H:%M:%S') if r.report_date else '',
                        'repair_status': r.repair_status,
                        'actual_completion_date': r.actual_completion_date,
                        'repair_duration': r.repair_duration,
                        'repair_person': r.repair_person,
                        'repair_company': r.repair_company,
                        'repair_type': r.repair_type,
                        'repair_content': r.repair_content,
                        'repair_cost': r.repair_cost,
                        'parts_replaced': r.parts_replaced,
                        'repair_result': r.repair_result,
                        'remarks': r.remarks,
                    })
            # 按钮可用性和样式逻辑
            enabled_style = {
                "cursor": "pointer",
                "boxShadow": "1px 1px 3px #bbb"
            }
            disabled_style = {
                "cursor": "not-allowed",
                "opacity": 0.65,
                "backgroundColor": "#cccccc",
                "boxShadow": "1px 1px 3px #bbb"
            }
            selected_repair_id = None
            if active_cell is not None and data:
                row = active_cell.get('row', 0)
                if 0 <= row < len(data):
                    row_data = data[row]
                    selected_repair_id = row_data.get('id')
                    repair_status = row_data.get('repair_status', '')
                    disabled1 = repair_status != '待响应'
                    disabled2 = repair_status not in ['维修中', '未完成']
                    disabled3 = repair_status not in ['维修中', '已修复','已完成']
                    style1 = disabled_style if disabled1 else enabled_style
                    style2 = disabled_style if disabled2 else enabled_style
                    style3 = disabled_style if disabled3 else enabled_style
                    # print(f"p167 selected_repair_id: {selected_repair_id},{repair_status},{row_data}")

            return data, page_count, disabled1, disabled2, disabled3, style1, style2, style3, selected_repair_id
        

        except Exception as e:
            print(f"!!! ERROR in update_repair_table_and_buttons: {e}")
            import traceback
            traceback.print_exc()
            data = []
            page_count = 0
            disabled1 = disabled2 = disabled3 = True
            style1 = style2 = style3 = {
                "cursor": "not-allowed",
                "opacity": 0.65,
                "backgroundColor": "#cccccc",
                "boxShadow": "1px 1px 3px #bbb"
            }
            selected_repair_id = None  # 在这里初始化变量
            # 异常处理块中
            
            
            
            # 确保返回语句中的变量都已定义
            return data, page_count, disabled1, disabled2, disabled3, style1, style2, style3, selected_repair_id